#include "hw_key.h"
#include "lcd/lcd.h"
#include "motor/hw_motor.h"
#include "ui/app.h"
#include "utils/multi_button.h"
#include <stdint.h>
#include <string.h>
#include "page_manager.h"

// 按键对象定义
static struct Button btn_up;
static struct Button btn_down;
static struct Button btn_left;
static struct Button btn_right;
static struct Button btn_ok;

static void update_motor_speed(char mode);

// 按键读取函数
static uint8_t read_button_gpio(uint8_t button_id)
{
    uint8_t value = 1;
    switch (button_id)
    {
    case 0: // UP
        value = (DL_GPIO_readPins(GPIO_KEY_UP_PORT, GPIO_KEY_UP_PIN) & GPIO_KEY_UP_PIN) ? 1 : 0;
        break;
    case 1: // DOWN
        value = (DL_GPIO_readPins(GPIO_KEY_DOWN_PORT, GPIO_KEY_DOWN_PIN) & GPIO_KEY_DOWN_PIN) ? 1 : 0;
        break;
    case 2: // LEFT
        value = (DL_GPIO_readPins(GPIO_KEY_LEFT_PORT, GPIO_KEY_LEFT_PIN) & GPIO_KEY_LEFT_PIN) ? 1 : 0;
        break;
    case 3: // RIGHT
        value = (DL_GPIO_readPins(GPIO_KEY_RIGHT_PORT, GPIO_KEY_RIGHT_PIN) & GPIO_KEY_RIGHT_PIN) ? 1 : 0;
        break;
    case 4: // OK
        value = (DL_GPIO_readPins(GPIO_KEY_OK_PORT, GPIO_KEY_OK_PIN) & GPIO_KEY_OK_PIN) ? 1 : 0;
        break;
    }

    return value;
}

static void btn_callback(void* button)
{
		uint8_t btn_event = get_button_event((struct Button *)button);
    PageParam param = { .data.button.buttonEvent = btn_event, .data.button.buttonId = ((struct Button *)button)->button_id };
    PageManager_DispatchEvent(PAGE_EVENT_KEY_PRESS, &param);
}

// 按键初始化
void key_init(void)
{
    // 初始化UP按键
    button_init(&btn_up, read_button_gpio, 0, 0); // active_level=0 表示低电平有效
    button_attach(&btn_up, SINGLE_CLICK, btn_callback);
    button_attach(&btn_up, LONG_PRESS_START, btn_callback);
    button_attach(&btn_up, LONG_PRESS_HOLD, btn_callback);
    button_start(&btn_up);

    // 初始化DOWN按键
    button_init(&btn_down, read_button_gpio, 0, 1);
    button_attach(&btn_down, SINGLE_CLICK, btn_callback);
    button_attach(&btn_down, LONG_PRESS_START, btn_callback);
    button_attach(&btn_down, LONG_PRESS_HOLD, btn_callback);
    button_start(&btn_down);

    // 初始化LEFT按键
    button_init(&btn_left, read_button_gpio, 0, 2);
    button_attach(&btn_left, SINGLE_CLICK, btn_callback);
    button_start(&btn_left);

    // 初始化RIGHT按键
    button_init(&btn_right, read_button_gpio, 0, 3);
    button_attach(&btn_right, SINGLE_CLICK, btn_callback);
    button_start(&btn_right);

    // 初始化OK按键
    button_init(&btn_ok, read_button_gpio, 0, 4);
    button_attach(&btn_ok, SINGLE_CLICK, btn_callback);
    button_start(&btn_ok);
}

// 按键扫描函数
void key_scan(void)
{
    button_ticks();
}